<?php

namespace app\common;

/**
 * 树形 class
 */
class Tree
{
    protected array $data;
    protected string $pid;
    protected string $child;

    /**
     * 构造 function
     *
     * @param array $data
     * @param string $pid
     * @param string $child
     */
    public function __construct(array $data, string $pid = "pid", string $child = "children")
    {
        $this->data = $data;
        $this->pid = $pid;
        $this->child = $child;
    }

    /**
     * 生成 function
     *
     * @param integer $parentId
     * @return array
     */
    public function buildTree($parentId = 0): array
    {
        $tree = [];

        foreach ($this->data as $node) {
            if ($node[$this->pid] == $parentId) {
                $children = $this->buildTree($node['id']);
                if (!empty($children)) {
                    $node[$this->child] = $children;
                }

                $tree[] = $node;
            }
        }

        return $tree;
    }
}
